/**
 * 
 */
package java8;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author dinghn
 *
 */
public class Java8 {
	public static void main(String[] args) throws Exception {
		testMap();

		// testStream();
	}

	private static void testMap() {
		HashMap<String, String> map = new HashMap<String, String>() {
			{
				put("a", "b");
				put("b", "c");
			}
		};
		map.forEach((id, value) -> System.out.println(String.format("%s:%s",
				id, value)));
		map.replaceAll((id, value) -> id+value);
		map.forEach((id, value) -> System.out.println(String.format("%s:%s",
				id, value)));
		map.compute("a", (a,b)->a+"aaa"+b);
		map.forEach((id, value) -> System.out.println(String.format("%s:%s",
				id, value)));
		map.merge("b", "bbb", String::concat);
		map.forEach((id, value) -> System.out.println(String.format("%s:%s",
				id, value)));
	}

	/**
	 * @throws Exception
	 */
	private static void testStream() throws Exception {
		// filter toMap toList
		ArrayList<String> list = new ArrayList<String>();
		list.add("a");
		list.add("b");
		Map<Integer, String> map = list.stream().collect(
				Collectors.toMap(String::hashCode, (a) -> a.toString()));
		System.out.println(map);
		String first = list.stream().filter(s -> s.equals("a")).findFirst()
				.orElseThrow(() -> new Exception());
		System.out.println(first);
		List<String> collect = list.stream().filter(s -> s.equals("a"))
				.collect(Collectors.toList());
		System.out.println(collect);

		// sort
		System.out.println(list);
		list.sort(Comparator.comparing(p -> p.hashCode())
				.thenComparing(p -> p.toString()).reversed());
		System.out.println(list);

		// fork/join
		ArrayList<Runnable> runs = new ArrayList<Runnable>();
		runs.add(new Runnable() {
			@Override
			public void run() {
				System.out.println(1);
			}
		});
		runs.add(new Runnable() {
			@Override
			public void run() {
				System.out.println(2);
			}
		});
		runs.parallelStream().forEach(s -> s.run());
		System.out.println();
	}
}
